﻿using UnityEngine;
using UnityEditor;
using System.Collections;

[CustomEditor (typeof(BackTile))]

public class BackTileEditor : Editor {
	
	BackTile selectedTile = null;
	static int max_grid_x = 200;
	static int max_grid_y = 200;
	Vector3 [,] gridTilePos;	
	
	void OnSceneGUI()
	{
		if(selectedTile!=null)
		{
			float sx = selectedTile.transform.position.x;
			float sy = selectedTile.transform.position.y;
			Vector3 newPos = GetGridPos(sx,sy);
			newPos.z = selectedTile.transform.position.z;
			selectedTile.transform.position = newPos;
		}		
	}
	
	void OnEnable() 
	{
		gridTilePos = new Vector3[max_grid_x,max_grid_y];
		float step_x = 0.54896f;//0.5585835f ;//for height 720
		float step_y = 0.27491122f;
		
		//float step_x = 2.19584f;
		//float step_y = 1.0996453f;
		
//0.2813334f ;//for height 720
		float step_z = 0.0001f;
		float tz = 2;
		int halfGridX = max_grid_x/2;
		int halfGridY = max_grid_y/2;
		for(int y=0; y<max_grid_y; y++)
		{
			for(int x=0; x< max_grid_x; x++)
			{
				gridTilePos[x,y] = new Vector3( (x-halfGridX)*step_x, (y-halfGridY)*step_y, tz);
			}
			//tz += step_z;
		}
		selectedTile = target as BackTile;		
		

	}
	
	Vector3 GetGridPos(float sx, float sy)
	{
		for(int y=0; y<max_grid_y; y++)
		{
			for(int x=0; x< max_grid_x-1; x++)
			{
				if(sx>=gridTilePos[x,y].x && sx<gridTilePos[x+1,y].x && sy>=gridTilePos[x,y].y && sy<gridTilePos[x,y+1].y)
					return gridTilePos[x,y];
			}
		}		
		return new Vector3(sx,sy,0);
	}	
}
